var dgram = require("dgram");
var udpClient = dgram.createSocket("udp4");
import YAML from 'yamljs';
const Settings = YAML.load('settings.yaml');
const WS100_SHARE_SETTINGS = Settings.WS100_SHARE_SETTINGS;
const isUsed = WS100_SHARE_SETTINGS.enLed ? WS100_SHARE_SETTINGS.enLed : false;
const port = WS100_SHARE_SETTINGS.ledPort ? WS100_SHARE_SETTINGS.ledPort : 8800;
const ip = WS100_SHARE_SETTINGS.ledHost ? WS100_SHARE_SETTINGS.ledHost : "192.168.1.100";
//前导标识      总长度（低在前）   消息类型  发送ID          指令长度         种类编号   颜色（高4颜色，低4后缀颜色）  字体字号   数据长   数据       后导标识                            
//FE 5C 4B 89  1A 00 00 00     65       00 00 00 00    07 00 00 00     29 00    FF                          FF      02     31 32      FF FF
//FE5C4B89     1A 00 00 00     65       00000000       07000000        01 00    FF                          FF      02     0102FFFF
/**
 * 指令打包
 * @param num 
 * @param data 
 * @returns 
 */
function packetCmd(num: number, data: string) {
    let len = 24 + data.length;
    console.log(len, Buffer.from(data, 'utf8'));
    const payload = Buffer.alloc(len);
    payload.writeUInt8(0xfe, 0);
    payload.writeUInt8(0x5C, 1);
    payload.writeUInt8(0x4B, 2);
    payload.writeUInt8(0x89, 3);
    /*------------总长度------------- */
    payload.writeUInt32LE(0x18 + data.length, 4);
    /*------------消息类型------------- */
    payload.writeUInt8(0x65, 8);
    /*------------发送ID------------- */
    payload.writeUInt32LE(0, 9);
    /*------------指令长度------------- */
    payload.writeUInt32LE(5 + data.length, 13);
    /*------------种类编号------------- */
    payload.writeUInt16LE(num, 17);
    /*------------颜色------------- */
    payload.writeUInt8(0xff, 19);
    /*------------字体字号------------- */
    payload.writeUInt8(0xff, 20);
    /*------------数据长度------------- */
    payload.writeUInt8(data.length, 21);
    for (let i = 0; i < data.length; i++) {
        payload.writeUInt8(Buffer.from(data[i], 'ascii')[0], 22 + i);
    }
    payload.writeUInt8(0xff, 22 + data.length);
    payload.writeUInt8(0xff, 23 + data.length);

    console.log(payload.toString('hex').toUpperCase())
    return payload;
}
var iconv = require('iconv-lite');
//前导标识      总长度（低在前）   消息类型  发送ID          指令长度         种类编号   颜色（高4颜色，低4后缀颜色）  字体字号   数据长   数据       后导标识                            
//FE 5C 4B 89  1A 00 00 00     65       00 00 00 00    07 00 00 00     29 00    FF                          FF      02     31 32      FF FF
//FE5C4B89     1A 00 00 00     65       00000000       07000000        01 00    FF                          FF      02     0102FFFF
/**
 * 打包GB2312指令
 * @param num 
 * @param data 
 * @returns 
 */
function packetGB2312Cmd(num: number, data: string) {
    let dataDecode = iconv.encode(data, 'gb2312');
    console.log(dataDecode)
    let len = 24 + dataDecode.length;
    console.log(len);
    const payload = Buffer.alloc(len);
    payload.writeUInt8(0xfe, 0);
    payload.writeUInt8(0x5C, 1);
    payload.writeUInt8(0x4B, 2);
    payload.writeUInt8(0x89, 3);
    /*------------总长度------------- */
    payload.writeUInt32LE(0x18 + dataDecode.length, 4);
    /*------------消息类型------------- */
    payload.writeUInt8(0x65, 8);
    /*------------发送ID------------- */
    payload.writeUInt32LE(0, 9);
    /*------------指令长度------------- */
    payload.writeUInt32LE(5 + dataDecode.length, 13);
    /*------------种类编号------------- */
    payload.writeUInt16LE(num, 17);
    /*------------颜色------------- */
    payload.writeUInt8(0xff, 19);
    /*------------字体字号------------- */
    payload.writeUInt8(0xff, 20);
    /*------------数据长度------------- */
    payload.writeUInt8(dataDecode.length, 21);
    for (let i = 0; i < dataDecode.length; i++) {
        payload.writeUInt8(dataDecode[i], 22 + i);
    }
    payload.writeUInt8(0xff, 22 + dataDecode.length);
    payload.writeUInt8(0xff, 23 + dataDecode.length);

    console.log(payload.toString('hex').toUpperCase())
    return payload;
}
/**
 * 发送LED参数
 * @param num 
 * @param data 
 * @param isGb2312 
 */
function SendLedParams(num: number, data: string, isGb2312: boolean) {
    if (isUsed) {
        console.log(num, data, isGb2312)
        if (isGb2312) {
            udpClient.send(packetGB2312Cmd(num, data), port, ip)
        } else {
            udpClient.send(packetCmd(num, data), port, ip)
        }
    }
}

if (isUsed) {
    process.stdin.on("data", function (data) {
        console.log(data)

    })

    udpClient.on("message", function (message, rxinfo) {
        console.log(`服务器接收到来自 ${rxinfo.address}:${rxinfo.port} 的 ${Buffer.from(message).toString('hex')}`);
        //udpClient.send("收到消息后返回", rxinfo.port, rxinfo.address)
    });


    udpClient.on('listening', () => {
        const address = udpClient.address();
        console.log(`服务器监听 ${address.address}:${address.port}`);
    });
}
export { SendLedParams }
// udpClient.send(packetCmd(1, '12.3'), 8800, "192.168.0.100")
// udpClient.send(packetCmd(3, '10000'), 8800, "192.168.0.100")
// udpClient.send(packetCmd(4, '25.6'), 8800, "192.168.0.100")
// udpClient.send(packetCmd(5, '100'), 8800, "192.168.0.100")
// udpClient.send(packetGB2312Cmd(2, '东'), 8800, "192.168.0.100")
// udpClient.send(packetGB2312Cmd(6, '否'), 8800, "192.168.0.100")